package cq.zhcqk.fragment._2_dj;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.bean.BuildBean;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.apache.http.Header;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cq.zhcqk.R;
import cq.zhcqk.activity.LoginActivity;
import cq.zhcqk.adapter.GridviewAdapter;
import cq.zhcqk.alipay.PayResult;
import cq.zhcqk.app;
import cq.zhcqk.util.AsyncHttpClientUtils;
import cq.zhcqk.util.CheckLogin;
import cq.zhcqk.util.Common;
import cq.zhcqk.util.GsonUtil;
import cq.zhcqk.util.StringUtil;
import cq.zhcqk.util.wxapi.Constants;
import cq.zhcqk.widget.MyGridView;

/**
 * Created by zhangle on 2017/11/25.
 */
public class _3_DfFragment extends Fragment implements View.OnClickListener{
    private View view;
    private static Context context;
    private AsyncHttpClient httpClient;
    protected BuildBean buildBean;

    Map<String, Object> mapData;

    private static EditText idno;
    private Button search;

    private TextView sb_dzb;
    private TextView sb_name;
    private TextView sb_phone;
    private TextView sb_sfzh;
    private TextView sb_totlem;
    private TextView num;
    private ImageView reduce;
    private ImageView add;
    private MyGridView time_gl;
    private LinearLayout zhifb;
    private LinearLayout wxpay;
    private static LinearLayout data_lay;

    private ArrayList<String> times = new ArrayList<>();
    private GridviewAdapter mAdapter;

    private int totleNum = 0;
    private double totlePrice = 0;
    private double singlePrice = 0;

    private static final int SDK_PAY_FLAG = 1;

    /** popup窗口里的ListView */
    private ListView mTypeLv;
    /** 数据适配器 */
    private ArrayAdapter<String> testDataAdapter;
    /** popup窗口 */
    private PopupWindow typeSelectPopup;
    /** 模拟的假数据 */
    private List<String> listPop;
    private TextView dz_title;

    List<Map<String, Object>> monthData;

    private String year = "";

    private IWXAPI api;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if(view==null){
            view = inflater.inflate(R.layout.fragment_df_2_3, container, false);
            httpClient = AsyncHttpClientUtils.getInstance().getAsyncHttpClient();
            context = getActivity();
            api = WXAPIFactory.createWXAPI(context, null);
            initView();
        }
        ViewGroup parent=(ViewGroup)view.getParent();
        if(parent!=null){
            parent.removeView(view);
        }
        return view;
    }
    private void initView(){
        buildBean = DialogUIUtils.showLoading(context, "加载中...", true, true, true, false);
        idno = (EditText) view .findViewById(R.id.idno);
        search = (Button) view .findViewById(R.id.search);
        sb_dzb = (TextView) view.findViewById(R.id.sb_dzb);
        sb_name = (TextView) view.findViewById(R.id.sb_name);
        sb_phone = (TextView) view.findViewById(R.id.sb_phone);
        sb_sfzh = (TextView) view.findViewById(R.id.sb_sfzh);
        sb_totlem = (TextView) view.findViewById(R.id.sb_totlem);
        num = (TextView) view.findViewById(R.id.num);
        dz_title = (TextView) view.findViewById(R.id.dz_title);
        reduce = (ImageView) view.findViewById(R.id.reduce);
        add = (ImageView) view.findViewById(R.id.add);
        time_gl = (MyGridView) view .findViewById(R.id.time_gl);
        zhifb = (LinearLayout) view .findViewById(R.id.zhifb);
        wxpay = (LinearLayout) view .findViewById(R.id.wxpay);

        data_lay = (LinearLayout) view .findViewById(R.id.data_lay);
        time_gl.setSelector(new ColorDrawable(Color.TRANSPARENT));
        time_gl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(GridviewAdapter.getIsSelected().get(position)){
                    GridviewAdapter.getIsSelected().put(position, false);
                    cgNum(position,false);
                }else{
                    GridviewAdapter.getIsSelected().put(position, true);
                    cgNum(position,true);
                }
                mAdapter.notifyDataSetChanged();
            }
        });

        search.setOnClickListener(this);
        reduce.setOnClickListener(this);
        add.setOnClickListener(this);
        zhifb.setOnClickListener(this);
        dz_title.setOnClickListener(this);
        wxpay.setOnClickListener(this);
    }

    private void cgNum(int position,boolean isAdd){
        Map<String, Object> mapCheck = monthData.get(position);
        if(mapCheck.get("monthPay") == null){
            Toast.makeText(context,"当前月需缴纳金额不存在",Toast.LENGTH_SHORT).show();
            return;
        }
        double choosePrice = (double) mapCheck.get("monthPay");
        if(isAdd){
            totlePrice +=choosePrice;
//            totleNum += 1;
        }else{
//            totleNum = totleNum-1;
            totlePrice -= choosePrice;
        }
//        totlePrice = singlePrice*totleNum;
        BigDecimal b = new BigDecimal(totlePrice);
        totlePrice = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
        num.setText(""+totleNum);
        sb_totlem.setText("¥"+totlePrice);
    }

    private void setPriceNull(){
        totlePrice = 0;
        totleNum = 0;
        num.setText(""+totleNum);
        sb_totlem.setText("¥"+totlePrice);
    }

    /**
     * 初始化数据
     */
    private void initMonthData(Map<String, Object> map) {
        setPriceNull();
        if(map.get("data") == null){
            Toast.makeText(context,"未获取到待缴纳的月份",Toast.LENGTH_SHORT).show();
            return;
        }
        monthData = (List<Map<String, Object>>) map.get("data");
        times.clear();
        for (Map<String, Object> mapDetail:monthData) {
            times.add(mapDetail.get("month")+" 月");
        }
        mAdapter = new GridviewAdapter(times, context);
        time_gl.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.search:
                if(!app.isLogin){
                    Toast.makeText(context,"请先登录",Toast.LENGTH_SHORT).show();
                    context.startActivity(new Intent(context, LoginActivity.class));
                    getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                    return;
                }
                String no = idno.getText()+"";
                if(no == null || "".equals(no)){
                    Toast.makeText(context,"请输入身份证号码",Toast.LENGTH_SHORT).show();
                    return;
                }
                getDetail(no);
                break;
            case R.id.reduce:
//                cgNum(false);
                break;
            case R.id.add:
//                cgNum(true);
                break;
            case R.id.zhifb:
//                Toast.makeText(context,"正在开发",Toast.LENGTH_SHORT).show();
                if(!app.isLogin){
                    Toast.makeText(context,"请先登录",Toast.LENGTH_SHORT).show();
                    return;
                }
                getOrderInfo(1);
                break;
            case R.id.wxpay:
//                Toast.makeText(context,"正在开发",Toast.LENGTH_SHORT).show();
                if(!app.isLogin){
                    Toast.makeText(context,"请先登录",Toast.LENGTH_SHORT).show();
                    return;
                }
                getOrderInfo(2);
                break;
            case R.id.dz_title:
                // 使用isShowing()检查popup窗口是否在显示状态
                if (typeSelectPopup != null && !typeSelectPopup.isShowing()) {
                    typeSelectPopup.showAsDropDown(dz_title, 0, 10);
                }
                break;
        }
    }

    private void setData(Map<String, Object> map){
        sb_dzb.setText(map.get("deptname")+"");
        sb_name.setText(map.get("realname")+"");
        sb_phone.setText(map.get("var01")+"");
        sb_sfzh.setText(map.get("idcard")+"");
        sb_totlem.setText("¥"+0);
        if(map.get("monthmoney") != null){
            singlePrice = (double) map.get("monthmoney");
        }
        if(map.get("stringList") == null){
            return;
        }
        listPop = (List<String>) map.get("stringList");
        if(listPop != null && listPop.size()>0){
            year = listPop.get(0);
            dz_title.setText(year);
            getMonthInfo(year);
            initSelectPopup();
        }

//        for (int i=0;i<listDz.size();i++){
//            listPop.add(listDz.get(i).get("name")+"");
//        }
    }

    private void getDetail(String no){
        buildBean.show();
        RequestParams params = new RequestParams();
        params.add("idcard",no);
        httpClient.post(Common.URL+Common.IDCARDINFO,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                if(StringUtil.stringToInt(map.get("code")+"") != 0){
                    Toast.makeText(context,"没有党员信息,请检查身份证是否正确",Toast.LENGTH_SHORT).show();
                    data_lay.setVisibility(View.GONE);
                    return;
                }
                mapData = (Map<String, Object>) map.get("data");
                if(map != null){
                    data_lay.setVisibility(View.VISIBLE);
                    setData(mapData);
                }else {
                    Toast.makeText(context,"没有党员信息",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("errorResponse："+errorResponse);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("responseString："+responseString);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }

    private void getMonthInfo(String year){
        buildBean.show();
        RequestParams params = new RequestParams();
        params.add("idcard",mapData.get("idcard")+"");
        params.add("year",year);
        httpClient.post(Common.URL+Common.YEARPAY,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccessYEARPAY："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                initMonthData(map);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("errorResponse："+errorResponse);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("responseString："+responseString);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }

    private void getOrderInfo(final int payType){

        StringBuilder month = new StringBuilder();
        HashMap<Integer,Boolean> map = GridviewAdapter.getIsSelected();
        for(int i = 0; i < monthData.size(); i++){
            if(map.get(i)){
                month.append(monthData.get(i).get("month")+"").append(",");
            }
        }
        if(month.length() == 0){
            Toast.makeText(context,"请选择缴纳月份",Toast.LENGTH_SHORT).show();
            return;
        }
        RequestParams params = new RequestParams();
        params.add("idCard",mapData.get("idcard")+"");
        params.add("money",totlePrice+"");
        params.add("month",month.deleteCharAt(month.length()-1).toString());
        params.add("payType",payType+"");
        params.add("year",year);
        params.add("monthNum","1");
        System.out.println(params);
        String url = "";
        if(payType == 1){
            url = Common.URL+Common.CREATE;
        }else if(payType == 2){
            url = Common.URL+Common.WXPREPAY;
        }
        buildBean.show();
        httpClient.post(url,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                if(StringUtil.stringToInt(map.get("code")+"") != 0){
                    Toast.makeText(context,"没有党员信息,请检查身份证是否正确",Toast.LENGTH_SHORT).show();
                    data_lay.setVisibility(View.GONE);
                    return;
                }
                if(map.get("data") == null || "".equals(map.get("data")+"")){
                    Toast.makeText(context,"支付失败，请稍后再试",Toast.LENGTH_SHORT).show();
                }else{
                    if(payType == 1){
                        payV2(map.get("data")+"");
                    }else if(payType == 2){
                        wxPay((Map<String, Object>)map.get("data"));
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("errorResponse："+errorResponse);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("responseString："+responseString);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }

    /**
     * 发起支付宝支付
     * @param orderInfo
     */
    public void payV2(final String orderInfo) {
        if (StringUtil.isNull(orderInfo)){
            Toast.makeText(context, "获取订单数据失败", Toast.LENGTH_SHORT).show();
            return;
        }

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();
                        data_lay.setVisibility(View.GONE);
                        idno.setText("");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(context, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };

    public static void payNot(int payResultResult){
        if(payResultResult != 0){
            Toast.makeText(context, "支付失败", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();
            data_lay.setVisibility(View.GONE);
            idno.setText("");
        }
    }

    /**
     * 微信支付
     * @param orderInfo
     */
    private void wxPay(Map<String, Object> orderInfo){
        PayReq req = new PayReq();
//        req.appId			= orderInfo.get("appid")+"";
        req.appId			= Constants.APP_ID;
        req.partnerId		= orderInfo.get("partnerid")+"";
        req.prepayId		= orderInfo.get("prepayid")+"";
        req.nonceStr		= orderInfo.get("noncestr")+"";
        req.timeStamp		= StringUtil.stringToInt(orderInfo.get("timestamp")+"")+"";
        req.packageValue	= orderInfo.get("package")+"";
        req.sign			= orderInfo.get("sign")+"";
        // 将该app注册到微信
        api.registerApp(Constants.APP_ID);
//        IWXMsg.registerApp;
        api.sendReq(req);
    }

    /**
     * 初始化popup窗口
     */
    private void initSelectPopup() {
        mTypeLv = new ListView(context);
        // 设置适配器
        testDataAdapter = new ArrayAdapter<String>(context, R.layout.popup_text_item, listPop);
        mTypeLv.setAdapter(testDataAdapter);

        // 设置ListView点击事件监听
        mTypeLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 在这里获取item数据
                String value = listPop.get(position);
                // 把选择的数据展示对应的TextView上
                dz_title.setText(value);
                getMonthInfo(value);
                year = listPop.get(position);
                // 选择完后关闭popup窗口
                typeSelectPopup.dismiss();
            }
        });
        typeSelectPopup = new PopupWindow(mTypeLv, dz_title.getWidth(), ActionBar.LayoutParams.WRAP_CONTENT, true);
        // 取得popup窗口的背景图片
        Drawable drawable = ContextCompat.getDrawable(context, R.drawable.bg_corner);
        typeSelectPopup.setBackgroundDrawable(drawable);
        typeSelectPopup.setFocusable(true);
        typeSelectPopup.setOutsideTouchable(true);
        typeSelectPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // 关闭popup窗口
                typeSelectPopup.dismiss();
            }
        });
    }
}
